<template>
  <el-container>
    <el-header>
      <el-row :gutter="20">
        <el-col :span="16">
          <h1>
            <router-link to="/register" tag="span">睿那体育账号注册</router-link>
          </h1>
        </el-col>
        <el-col :span="8">
          已有账号？
          <router-link to="/login" tag="span" class="to-login">
            点击登录账号
          </router-link>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="ruleForm2.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model.number="ruleForm2.tel"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verCode">
          <div class="ver_code_wrap">
            <el-input v-model.number="ruleForm2.verCode" class="ver_code"></el-input>
            <el-button v-if="canGet" type="primary" round @click="obtainVer"><span v-if="secondTime.isLoad">{{secondTime.time}}秒可再次发送</span><span v-else>免费接收验证码</span></el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
          <el-button @click="resetForm('ruleForm2')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer>
      <p>
        <small>&copy; 版权所有 睿那体育 RNTV</small>
        <small>&copy;产品开发商 羽戈科技 YG</small>
      </p>
    </el-footer>
  </el-container>
</template>
<script>
  import md5 from "md5";
  export default {
    name: "register",
    data() {
      //验证规则
      var validatePass = (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var checkTel = (rule, value, callback) =>{
        let reg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
        if (!reg.test(value)) {
          //验证没通过
          this.isTel = false;
          this.canGet = false;
          callback(new Error('请输入正确的手机号'));
        }
        this.isTel = true;
        this.canGet = true;
        callback()
      };
      var chaeckName = (rule, value ,callback) =>{
        // let reg = /^[\u4e00-\u9fa5_a-zA-Z]{6,15}/
        if(value.trim() ===''){
          callback(new Error('用户名不可为空或空格'));
        }else if(value.trim().length<6||value.trim().length>15){
          callback(new Error('请输入6-15位之间'));
        }
        callback()
      };
      return {
        canGet:false,
        secondTime:{
          isLoad:false,
          time:60
        },
        isLoading1:false,
        auth_code:'',
        redirect_url: this.GLOBAL.RNTY_SHOP_PC_URL,
        ruleForm2: {
          username:'',
          pass: '',
          checkPass: '',
          age: '',
          tel:'',
          varCode:''
        },
        rules2: {
          username:[
            {required: true, validator: chaeckName, trigger: 'blur' }
          ],
          pass: [
            {required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {required: true, validator: validatePass2, trigger: 'blur' }
          ],
          tel: [
            {required: true, validator: checkTel, trigger: 'blur' }
          ],
          verCode:[
            {required: true, message: '请填写验证码', trigger: 'blur' }
          ]
        },
        isTel:false
      };
    },
    created() {
      //判断是否属于睿那旗下产品
      this.auth_code = this.$cookie.get("auth_code");
      if (this.auth_code) {
        this.GLOBAL.isRN(this) 
      }
    },
    methods: {
      submitForm(formName) {
        this.auth_code = this.$cookie.get("auth_code");
        // this.GLOBAL.isRN(this)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // console.log('输入正确,正在发送注册请求')
            this.GLOBAL.request({
              method:"POST",
              baseURL:this.GLOBAL.API_ACCOUNT_RNTY_URL,
              url:"users/register",
              data: {
                username:this.ruleForm2.username,
                password_hash:md5(this.ruleForm2.pass),
                mobile:this.ruleForm2.tel,
                sms_code:this.ruleForm2.verCode
              }
            }).then(({data:data}) =>{
              this.$message({
                type: data.status? 'success':'error',
                message: data.message
              });
              if(data.status){
                  this.GLOBAL.request({
                  method: "post",
                  baseURL: this.GLOBAL.API_ACCOUNT_RNTY_URL,
                  url: "users/login",
                  data:{
                    username:this.ruleForm2.username,
                    password:md5(this.ruleForm2.pass),
                    remember: false
                  }
                }).then(({data:data})=>{
                    this.$cookie.set("rnty_access_token", data.data.access_token, { expires: 1, domain: '.ruinatiyu.com'});
                    // window.location.href = this.redirect_url
                    this.$router.push('/user')
                  }
                )
              }
            }).catch((err,callback)=>{
              // console.log(err);
              // this.$message({
              //   type: 'fail',
              //   message: err.data
              // });
            })
          } else {
            // console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      obtainVer(){
        if (this.isLoading1||this.secondTime.isLoad) {
          return
        }
        //倒计时
        this.isLoading1 = true;
        this.secondTime.isLoad = true;
        let timer = setInterval(()=>{
          if (this.secondTime.time==0) {
            clearInterval(timer)
            this.secondTime.isLoad = false;
            this.secondTime.time = 60;
            this.isLoading1 = false;
          }
          this.secondTime.time--
        },1000)
        if(this.isTel){
          this.GLOBAL.request({
            method: "POST",
            baseURL: this.GLOBAL.API_ACCOUNT_RNTY_URL,
            url: "scode/send",
            data: {
              mobile: this.ruleForm2.tel
            }
          }).then(data =>{
            if(data){
              this.$notify({
                title: '成功',
                message: '验证码发送成功',
                type: 'success'
              });
            }else{
              this.$notify.error({
                title: '错误',
                message: '验证码发送失败'
              });
            }
          })
        }
      }
    }
  };

</script>
<style scoped>
@import "../assets/css/register.css";
.to-login {
  color: #409eff;
  cursor: pointer;
}
.el-form {
  width: 30%;
  margin: 20px auto;
}
small {
  display: block;
  line-height: 30px;
}
.ver_code_wrap{
  display: flex;
  justify-content: flex-start;
}
</style>
